package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.tree.CommonTree;
import com.ruoyi.common.core.domain.tree.TreeHelper;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.comlbs.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.ElectricFence;
import com.ruoyi.system.domain.EquipmentManagement;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.VehicleManagement;
import com.ruoyi.system.domain.request.dept.CompanyExistNameParam;
import com.ruoyi.system.domain.tree.*;
import com.ruoyi.system.domain.vo.common.DeviceGps;
import com.ruoyi.system.domain.vo.equipment.EquipmentInfo;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.mapper.VehicleManagementMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.ComLbsUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private VehicleManagementMapper vehicleManagementMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private IEquipmentManagementService equipmentManagementService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private IElectricFenceService electricFenceService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 查询部门管理数据(带父节点)
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> selectDeptListWithParents(SysDept dept) {
        return deptMapper.selectDeptListWithParents(dept);
    }

    /**
     * 查询部门管理id数据
     *
     * @param dept 部门信息
     * @return 部门id集合
     */
    @Override
    @DataScope
    public List<Long> selectDeptIdList(SysDept dept) {
        return selectDeptList(dept).stream().map(SysDept::getDeptId).collect(Collectors.toList());
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @DataScope
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        List<SysDept> depts = selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 根据ID查询子孙ID
     *
     * @param deptId 部门ID
     * @return
     */
    @Override
    public List<Long> selectChildrenDeptId(Long deptId) {
        if (deptId == null) return null;
        List<Long> deptIdList = new ArrayList<>();
        deptIdList.add(deptId);
        List<SysDept> childrenDeptList = deptMapper.selectChildrenDeptById(deptId);
        if (ObjectUtils.isNotEmpty(childrenDeptList)) {
            deptIdList.addAll(childrenDeptList.stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        }
        return deptIdList;
    }

    /**
     * 查询有权限的部门ID，根据ID查询子孙ID并当前用户的权限取交集
     *
     * @param deptId 需要比较的部门ID
     * @return
     */
    @Override
    public List<Long> selectPermissionDeptId(Long deptId) {
        //当前用户的全部权限
        List<Long> allDeptIdList = selectDeptIdList(new SysDept());
        if (deptId == null) return allDeptIdList;
        //需要比较的权限,取交集
        List<Long> inputDeptIdList = selectChildrenDeptId(deptId);
        inputDeptIdList.retainAll(allDeptIdList);
        return inputDeptIdList;
    }

    @Override
    public List<Long> selectPermissionDeptIds(List<Long> deptIds) {
        //当前用户的全部权限
        List<Long> allDeptIdList = selectChildrenDeptId(SecurityUtils.getDeptId());
        if (ObjectUtils.isEmpty(deptIds)) return allDeptIdList;
        //需要比较的权限,取交集
        deptIds.retainAll(allDeptIdList);
        return deptIds;
    }

    public List<SysDept> selectPermissionDept(Long deptId) {
        List<SysDept> sysDepts = selectDeptList(new SysDept());
        if (CollectionUtils.isEmpty(sysDepts))
            return null;
        if (deptId == null) return sysDepts;

        //需要比较的权限,取交集
        List<Long> inputDeptIdList = selectChildrenDeptId(deptId);
        if (CollectionUtils.isEmpty(inputDeptIdList))
            return null;
        List<SysDept> collect = sysDepts.stream()
                .filter(x -> inputDeptIdList.contains(x.getDeptId()))
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在设备
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public void checkDeptExistDevice(Long deptId) {
        List<Long> deptIdList = selectChildrenDeptId(deptId);
        int count = equipmentManagementService.count(new QueryWrapper<EquipmentManagement>().in("company_id", deptIdList));
        if (count > 0) throw new ServiceException("节点存在设备，不允许删除");
        count = vehicleManagementMapper.selectCount(new QueryWrapper<VehicleManagement>().in("company_id", deptIdList));
        if (count > 0) throw new ServiceException("节点存在监管对象，不允许删除");
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        if (dept.getParentId() == 0) {
            //顶级节点
            dept.setAncestors("0");
        } else {
            SysDept info = deptMapper.selectDeptById(dept.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("部门停用，不允许新增");
            }
            dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        }
        return deptMapper.insert(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(oldDept)) {
            String newAncestors;
            if (StringUtils.isNull(newParentDept)) {  // 改到根节点下
                newAncestors = "0";
            } else {
                newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            }
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors()) && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        for (SysDept n : list) {
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 查询公司名称是否已存在
     *
     * @param param
     */
    @Override
    public void checkExistName(CompanyExistNameParam param) {
        List<SysDept> ancestorsDeptList;
        if (param.getParentId() == 0) {
            //顶级节点
            ancestorsDeptList = deptMapper.selectList(new QueryWrapper<SysDept>()
                    .eq("parent_id", 0).eq("del_flag", "0"));
        } else {
            //非顶级节点，找出所有祖先节点，进行对比
            ancestorsDeptList = deptMapper.selectChildrenDeptById(SecurityUtils.getRootDeptId());
        }
        if (param.getCompanyId() != null) {
            //是编辑，先移除本身公司
            ancestorsDeptList.removeIf(dept -> dept.getDeptId().equals(param.getCompanyId()));
        }
        List<String> ancestorsDeptNameList = ancestorsDeptList.stream().map(SysDept::getDeptName).collect(Collectors.toList());
        if (ancestorsDeptNameList.contains(param.getCompanyName())) throw new ServiceException("该公司名称已存在");
    }

    /**
     * 查询列表(附加总车辆数)
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @DataScope
    @Override
    public List<SysDept> selectDeptListWithVehicleCount(SysDept dept) {
        return deptMapper.selectDeptListWithVehicleCount(dept);
    }

    /**
     * 视频页面设备树，含通道
     *
     * @return
     */
    @Override
    public List<VideoTree> videoTree(Boolean onlyOnline) {
        //初始化树列表，首先获取公司列表
        List<VideoTree> treeList = selectDeptListWithParents(new SysDept()).stream()
                .map(VideoTree::new)
                .collect(Collectors.toList());
        // 先构造组织架构树(重组爷孙关系)，再转换为list，放入其余节点，重新构树
        treeList = TreeHelper.treeToList(TreeHelper.buildTree(treeList));
        //获取设备在线信息
        Map<String, DeviceGps> onlineData = commonService.getDeviceOnlineDataFromCache();
        if (onlineData != null) {
            //查询已绑定车载设备的车辆集合
            List<VehicleManagement> vehicleManagementList = vehicleManagementMapper.listBindVehicle(new VehicleManagement());
            //将车辆放入公司列表中，防止同一辆车绑定多个设备
            Set<Long> vehicleIdSet = new HashSet<>();
            for (VehicleManagement vehicle : vehicleManagementList) {
                DeviceGps device = onlineData.get(vehicle.getDeviceId());
                if (device == null || StringUtils.isEmpty(vehicle.getChannelsNum()) || !vehicleIdSet.add(vehicle.getId())) {
                    continue;
                }
                //将车辆放入公司列表
                VehicleStatusEnum vehicleStatus = ComLbsUtils.getVehicleStatus(device);
                VideoTree vehicleTree = new VideoTree()
                        .setId("veh_" + vehicle.getId())
                        .setParentId(vehicle.getBindId().toString())
                        .setType(OrgTypeEnum.DEVICE.getCode())
                        .setLabel(vehicle.getNumberPlate())
                        .toExtentTree(VideoTree.class)
                        .setDeviceId(vehicle.getDeviceId())
                        .setStatus(vehicleStatus.getCode())
                        .setOnline(!vehicleStatus.equals(VehicleStatusEnum.OFFLINE));
                treeList.add(vehicleTree);
                //将通道放入公司列表
                String[] channels = vehicle.getChannelsNum().split(",");
                List<String> channelList = Arrays.asList(channels);
                Collections.sort(channelList);
                for (String channel : channelList) {
                    VideoTree channelTree = new VideoTree()
                            .setId("ch_" + vehicle.getDeviceId() + "_" + channel) //ch_设备号_通道号
                            .setParentId("veh_" + vehicle.getId())
                            .setLabel(OrgTypeEnum.CHANNEL.getText() + channel)  // 通道所属车辆的所属公司缩写
                            .setType(OrgTypeEnum.CHANNEL.getCode())
                            .toExtentTree(VideoTree.class)
                            .setDeviceId(vehicle.getDeviceId());
                    treeList.add(channelTree);
                }
            }
        }
        List<VideoTree> resTreeList = TreeHelper.buildTreeHasParent(treeList);
        resTreeList.stream().forEach(i -> ComLbsUtils.treeVehicleCount(i, onlyOnline));
        return resTreeList;
    }

    /**
     * 指令下发车辆树列表
     *
     * @return
     */
    @Override
    public List<CmdSendDeviceTree> orderSendDeviceTree() {
        //查询已激活设备集合
        List<EquipmentInfo> equipmentList = equipmentManagementService.selectList(new EquipmentInfo()
                .setActivateStatus(ActivateStatusEnum.ACTIVATED.getCode())
                .setNumberPlateNotEmpty(true));
        //获取公司树列表
        List<SysDept> deptList = selectDeptListWithParents(new SysDept());
        //获取设备在线信息
        Map<String, DeviceGps> onlineData = commonService.getDeviceOnlineDataFromCache();
        List<CmdSendDeviceTree> treeList = deptList.stream().map(CmdSendDeviceTree::new).collect(Collectors.toList());
        // 先构造组织架构树(重组爷孙关系)，再转换为list，放入其余节点，重新构树
        List<CmdSendDeviceTree> deptTree = TreeHelper.treeToList(TreeHelper.buildTree(treeList));
        for (EquipmentInfo equipment : equipmentList) {
            CmdSendDeviceTree tree = new CmdSendDeviceTree()
                    .setId("equip_" + equipment.getEquipmentId())
                    .setParentId(String.valueOf(equipment.getCompanyId()))
                    .setType(OrgTypeEnum.DEVICE.getCode())
                    .setLabel(equipment.getNumberPlate())
                    .toExtentTree(CmdSendDeviceTree.class)
                    .setDeviceId(equipment.getDeviceId())
                    .setObjIcon(equipment.getObjIcon())
                    .setOnlineStatus(ComLbsUtils.getObjectStatus(onlineData.get(equipment.getDeviceId()), equipment.getObjType()).getCode());
            deptTree.add(tree);
        }
        return TreeHelper.buildTreeHasParent(deptTree);
    }

    /**
     * 带父节点的组织架构树列表
     *
     * @return
     */
    @Override
    public List<CommonTree> treeListWithParents() {
        //获取公司树列表
        List<SysDept> deptList = selectDeptListWithParents(new SysDept());
        List<CommonTree> treeList = deptList.stream().map(CommonTree::new).collect(Collectors.toList());
        return TreeHelper.treeToList(TreeHelper.buildTree(treeList));
    }
    /**
     * 带父节点的组织架构树列表
     *
     * @return
     */
    @Override
    public List<DeptTree> treeListWithParentsRole(SysDept dept) {
        //获取公司树列表
        List<SysDept> deptList = selectDeptListWithParents(new SysDept());
        if(StringUtils.isNotNull(dept.getDeptId())) {
            deptList.removeIf(d -> !d.getDeptId().equals(dept.getDeptId()) && !ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), dept.getDeptId().toString()));
        }
        List<DeptTree> treeList = deptList.stream().map(DeptTree::new).collect(Collectors.toList());
        return treeList;
    }

    /**
     * 获取组织架构用户树列表
     *
     * @return
     */
    @Override
    public List<UserTree> userTree() {
        //获取企业列表
        List<SysDept> deptList = selectDeptListWithParents(new SysDept());
        //获取用户列表
        List<SysUser> sysUsers = userService.selectUserList(new SysUser());
        //查询用户角色关联信息
        List<Long> userIdList = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
        List<SysUserRole> userRoleList = userRoleMapper.selectList(new QueryWrapper<SysUserRole>().in("user_id", userIdList));
        Map<Long, List<Long>> userRoleMap = userRoleList.stream().collect(Collectors.groupingBy(SysUserRole::getUserId, Collectors.mapping(SysUserRole::getRoleId, Collectors.toList())));
        //组合数据
        List<UserTree> treeList = deptList.stream().map(UserTree::new).collect(Collectors.toList());
        // 先构造组织架构树(重组爷孙关系)，再转换为list，放入其余节点，重新构树
        treeList = TreeHelper.treeToList(TreeHelper.buildTree(treeList));
        List<UserTree> userList = sysUsers.stream().map(i -> new UserTree()
                .setId("userId_" + i.getUserId()) //防止用户id与公司id冲突
                .setParentId(i.getDeptId().toString())
                .setLabel(i.getNickName())
                .setType(OrgTypeEnum.PERSON.getCode())
                .toExtentTree(UserTree.class)
                .setRoleIds(userRoleMap.get(i.getUserId()))
        ).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(userList)) treeList.addAll(userList);
        return TreeHelper.buildTreeHasParent(treeList);
    }

    /**
     * 获取围栏树列表
     *
     * @return
     */
    @Override
    public JSONObjectPro polygonTree(ElectricFence param) {
        //获取企业列表
        List<SysDept> deptList = selectDeptListWithParents(new SysDept());
        //获取围栏列表
        List<ElectricFence> fenceList = electricFenceService.selectList(new ElectricFence());
        //统计数量
        int totalCount = fenceList.size();
        long polygonCount = fenceList.stream().filter(i ->
                i.getType() == FenceTypeEnum.POLYGON.getCode() || i.getType() == FenceTypeEnum.RECTANGLE.getCode()).count();
        long lineCount = fenceList.stream().filter(i -> i.getType() == FenceTypeEnum.LINE.getCode()).count();
        //组合数据
        if (param.getType() != null) {
            fenceList = fenceList.stream().filter(i -> i.getType() == param.getType().intValue()).collect(Collectors.toList());
        }
        List<PolygonTree> treeList = deptList.stream().map(PolygonTree::new).collect(Collectors.toList());
        // 先构造组织架构树(重组爷孙关系)，再转换为list，放入其余节点，重新构树
        treeList = TreeHelper.treeToList(TreeHelper.buildTree(treeList));
        for (ElectricFence i : fenceList) {
            PolygonTree item = new PolygonTree()
                    .setId(i.getId().toString())
                    .setParentId(i.getCompanyId())
                    .setLabel(i.getName())
                    .setType(OrgTypeEnum.POLYGON.getCode())
                    .toExtentTree(PolygonTree.class)
                    .setPolygonType(i.getType())
                    .setXyWgs84(i.getXyWgs84())
                    .setXyGcj02(i.getXyGcj02());
            treeList.add(item);
        }
        return new JSONObjectPro()
                .put("list", TreeHelper.buildTreeHasParent(treeList))
                .put("totalCount", totalCount)
                .put("polygonCount", (int) polygonCount)
                .put("lineCount", (int) lineCount);
    }

    /**
     * 获取出厂待销售公司
     *
     * @return
     */
    public SysDept getWaitSaleCompany() {
        String waitSaleCompanyId = configService.selectConfigByKey("wait_sale_company_id");
        SysDept dept = deptMapper.selectDeptById(Long.valueOf(waitSaleCompanyId));
        if (dept == null) throw new ServiceException("出厂待销售公司不存在");
        return dept;
    }
}
